import Vue from 'vue';
import VueRouter from 'vue-router';
import routes from './routes';
import store from '@/store';
import getMenu from '../utils/permission';
import Home from '../views/Layout/Home.vue';

Vue.use(VueRouter);

const router = new VueRouter({
  routes,
});

const newRouterMap = [
  {
    path: '/prodouct',
    name: 'Prodouct',
    meta: {
      title: '商品',
      hidden: false,
      icon: 'shopping',
    },
    component: Home,
    children: [
      {
        path: 'list',
        name: 'ProdouctList',
        meta: {
          title: '商品列表',
          hidden: false,
          icon: 'ordered-list',
        },
        component: () => import('@/views/page/ProdouctList.vue'),
      },
      {
        path: 'add',
        name: 'ProdouctAdd',
        meta: {
          title: '添加商品',
          hidden: false,
          icon: 'folder-add',
        },
        component: () => import('@/views/page/ProdouctAdd.vue'),
      },
      {
        path: 'edit/:id',
        name: 'ProdouctEdit',
        meta: {
          title: '编辑商品',
          hidden: true,
          icon: 'folder-add',
        },
        component: () => import('@/views/page/ProdouctAdd.vue'),
      },
      {
        path: 'category',
        name: 'Category',
        meta: {
          title: '类目管理',
          hidden: false,
          icon: 'snippets',
        },
        component: () => import('@/views/page/Category.vue'),
      },
    ],
  },
];

let isAdd = false; // 用于记录是否存储
router.beforeEach((to, from, next) => {
  /* must call `next` */
  if (to.path !== '/login') {
    if (store.state.user.user.appkey && store.state.user.user.username) {
      if (!isAdd) {
        const menuAll = getMenu(store.state.user.user.role, newRouterMap);

        store.dispatch('setMenuRoutes', routes.concat(menuAll)).then(() => {
          router.addRoutes(menuAll);
          next();
        });
        isAdd = true;
      }
      return next();
    }
    return next('/login');
  }
  return next();
});

export default router;
